package com.cn.gmall.list.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.cn.gmall.list.repository.GoodsRepository;
import com.cn.gmall.list.service.SearchService;
import com.cn.gmall.model.list.*;
import com.cn.gmall.model.product.BaseAttrInfo;
import com.cn.gmall.model.product.BaseCategoryView;
import com.cn.gmall.model.product.BaseTrademark;
import com.cn.gmall.model.product.SkuInfo;
import com.cn.gmall.product.client.ProductFeignClient;


import org.apache.lucene.search.join.ScoreMode;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;


import java.io.IOException;
import java.util.*;

import java.util.stream.Collectors;


@Service
@SuppressWarnings("all")
public class SearchServiceImpl implements SearchService {
    @Autowired
    private GoodsRepository goodsRepository;

    @Autowired
    private ProductFeignClient productFeignClient;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
//    es构建DSL的高级窗口类
    private RestHighLevelClient restHighLevelClient;

    /**
     * 商品搜索
     *
     * @param searchParam
     * @return
     */
    @Override
    public SearchResponseVo topSearchList(SearchParam searchParam) {

        SearchResponseVo searchResponseVo = null;
        try {
            SearchRequest searchRequest = this.builderDSL(searchParam);
//  发送请求到es
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

//     处理结果
            searchResponseVo = this.parsedSearchResponseVo(searchResponse);
//封装当前页
            searchResponseVo.setPageNo(searchParam.getPageNo());
            searchResponseVo.setPageSize(searchParam.getPageSize());
//      总页数=(总条数+每页条数-1)/每页条数
            searchResponseVo.setTotalPages((searchResponseVo.getTotal() + searchParam.getPageSize() - 1) / searchParam.getPageSize());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return searchResponseVo;
    }

    /***
     * 将返回对象的结果集转换为searchResponseVo
     * @param searchResponse
     * @return
     */
    private SearchResponseVo parsedSearchResponseVo(SearchResponse searchResponse) {
//     创建响应对象
        SearchResponseVo searchResponseVo = new SearchResponseVo();
//        获取所有的聚合数据
        Map<String, Aggregation> mapAllAgg = searchResponse.getAggregations().asMap();
        if (!CollectionUtils.isEmpty(mapAllAgg)) {
/**---------------------tmIdAgg对象----------------------
 *获 取品牌聚合对象
 *  ParsedLongTerms 是 Aggregation的子类 功能更强
 *  "tmIdAgg" : {
 *       "doc_count_error_upper_bound" : 0,
 *       "sum_other_doc_count" : 0,
 *       "buckets" : [
 *         {
 *           "key" : 1,
 *           "doc_count" : 4,
 *           "tmNameAgg" : {
 *             "doc_count_error_upper_bound" : 0,
 *             "sum_other_doc_count" : 0,
 *             "buckets" : [
 *               {
 *                 "key" : "小米",
 *                 "doc_count" : 4
 *               }
 *             ]
 *           },
 *           "tmLogoUrlAgg" : {
 *             "doc_count_error_upper_bound" : 0,
 *             "sum_other_doc_count" : 0,
 *             "buckets" : [
 *               {
 *                 "key" : "http://192.168.245.130:9000/gmall/20230728-194055-c3efile",
 *                 "doc_count" : 4
 *               }
 *             ]
 *           }
 *         },
 *         {
 *           "key" : 3,
 *           "doc_count" : 4,
 *           "tmNameAgg" : {
 *             "doc_count_error_upper_bound" : 0,
 *             "sum_other_doc_count" : 0,
 *             "buckets" : [
 *               {
 *                 "key" : "华为",
 *                 "doc_count" : 4
 *               }
 *             ]
 *           },
 *           "tmLogoUrlAgg" : {
 *             "doc_count_error_upper_bound" : 0,
 *             "sum_other_doc_count" : 0,
 *             "buckets" : [
 *               {
 *                 "key" : "http://192.168.245.130:9000/gmall/20230728-194121-3b7file",
 *                 "doc_count" : 4
 *               }
 *             ]
 *           }
 *         }
 *       ]
 *     },
 */
            ParsedLongTerms tmIdAgg = (ParsedLongTerms) mapAllAgg.get("tmIdAgg");
            if (tmIdAgg != null) {
                List<SearchResponseTmVo> tmVoList = tmIdAgg.getBuckets().stream().map(bucket -> {
                    SearchResponseTmVo tmIdAggSearchResponseVo = new SearchResponseTmVo();
//           品牌id
                    /*long tmId = bucket.getKeyAsNumber().longValue();
                    tmIdAggSearchResponseVo.setTmId(tmId);*/
                    tmIdAggSearchResponseVo.setTmId(bucket.getKeyAsNumber().longValue());
//      设置品牌名称
                    ParsedStringTerms tmNameAgg = (ParsedStringTerms) bucket.getAggregations().asMap().get("tmNameAgg");
                    tmIdAggSearchResponseVo.setTmName(tmNameAgg.getBuckets().get(0).getKeyAsString());

//            获取图片路径
                    ParsedStringTerms tmLogoUrlAgg = (ParsedStringTerms) bucket.getAggregations().asMap().get("tmLogoUrlAgg");
                    tmIdAggSearchResponseVo.setTmLogoUrl(tmLogoUrlAgg.getBuckets().get(0).getKeyAsString());

                    return tmIdAggSearchResponseVo;
                }).collect(Collectors.toList());
//                设置到返回对象里面
                searchResponseVo.setTrademarkList(tmVoList);
            }

//设置平台属性
            ParsedNested attrsAgg = (ParsedNested) mapAllAgg.get("attrsAgg");
//获取平台属性id聚合对象
            ParsedLongTerms attrIdAgg = (ParsedLongTerms) attrsAgg.getAggregations().asMap().get("attrIdAgg");
//        封装平台属性
            List<SearchResponseAttrVo> attrVoList = attrIdAgg.getBuckets().stream().map(bucket -> {
                SearchResponseAttrVo searchResponseAttrVo = new SearchResponseAttrVo();
                //设置平台属性id
                searchResponseAttrVo.setAttrId(bucket.getKeyAsNumber().longValue());

//                  //平台属性名
                ParsedStringTerms attrNameAgg = (ParsedStringTerms) bucket.getAggregations().asMap().get("attrNameAgg");
                searchResponseAttrVo.setAttrName(attrNameAgg.getBuckets().get(0).getKeyAsString());
                //设置平台属性值集合
//和老师不一样 attrValueAgg在attrNameAgg桶下面
                ParsedStringTerms attrValueAgg = (ParsedStringTerms) bucket.getAggregations().asMap().get("attrValueAgg");
//属性集合
                List<String> attrValueList = attrValueAgg.getBuckets().stream().map(subBucket -> {
                    return subBucket.getKeyAsString();
                }).collect(Collectors.toList());
//设置数据值集合
                searchResponseAttrVo.setAttrValueList(attrValueList);
                //返回封装平台对象
                return searchResponseAttrVo;
            }).collect(Collectors.toList());
            //设置到响应对象
            searchResponseVo.setAttrsList(attrVoList);

        }

        /***设置商品列表数据---------
         * "hits" : [
         *       {
         *         "_index" : "goods",
         *         "_type" : "_doc",
         *         "_id" : "21",
         *         "_score" : null,
         *         "_source" : {
         *           "defaultImg" : "http://192.168.245.130:9000/gmall/20230728-212541-ab2file",
         *           "price" : 999.0,
         *           "id" : 21,
         *           "title" : " 小米 CC9 手机 星空篮 6G +128G"
         *         },
         *         "highlight" : {
         *           "title" : [
         *             "小米 CC9 <font color='red'>手机</font> 星空篮 6G +128G"
         *           ]
         *         },
         *         "sort" : [
         *           10
         *         ]
         *       },
         *       {
         *         "_index" : "goods",
         *         "_type" : "_doc",
         *         "_id" : "23",
         *         "_score" : null,
         *         "_source" : {
         *           "defaultImg" : "http://192.168.245.130:9000/gmall/20230728-212548-c01file",
         *           "price" : 3699.0,
         *           "id" : 23,
         *           "title" : " 小米 CC9 手机 6G +128G 清新绿"
         *         },
         *         "highlight" : {
         *           "title" : [
         *             "小米 CC9 <font color='red'>手机</font> 6G +128G 清新绿"
         *           ]
         *         },
         *         "sort" : [
         *           0
         *         ]
         *       },
         *       {
         *         "_index" : "goods",
         *         "_type" : "_doc",
         *         "_id" : "28",
         *         "_score" : null,
         *         "_source" : {
         *           "defaultImg" : "http://192.168.245.130:9000/gmall/20230730-214146-b0dfile",
         *           "price" : 9299.0,
         *           "id" : 28,
         *           "title" : " 华为 荣耀V30 PRO 手机 冰河世纪 8G+256G 天玑9200"
         *         },
         *         "highlight" : {
         *           "title" : [
         *             "华为 荣耀V30 PRO <font color='red'>手机</font> 冰河世纪 8G+256G 天玑9200"
         *           ]
         *         },
         *         "sort" : [
         *           0
         *         ]
         *       }
         *     ]
         *
         */
        SearchHits hits = searchResponse.getHits();
        SearchHit[] searchHits = hits.getHits();

        if(searchHits!=null &&searchHits.length>0){
            //获取封装的商品列表 searchHits.strean()自动生成Arrays.stream(searchHits)
            List<Goods> goodsList = Arrays.stream(searchHits).map(hit -> {

                //获取数据
                String sourceAsString = hit.getSourceAsString();
                Goods goods = JSONObject.parseObject(sourceAsString, Goods.class);
                //设置高亮数据
                if(hit.getHighlightFields()!=null&&hit.getHighlightFields().get("title")!=null){

                    String title = hit.getHighlightFields().get("title").getFragments()[0].toString();
                    //设置高亮字段
                    goods.setTitle(title);
                }
                return goods;
            }).collect(Collectors.toList());
            searchResponseVo.setGoodsList(goodsList);
        }
        //设置分页数据
        //获取总记录数据
    /*    long totalSize = hits.getTotalHits().value;
        searchResponseVo.setTotal(totalSize);*/
        searchResponseVo.setTotal(hits.getTotalHits().value);

        return searchResponseVo;
    }

    /**
     * 生成查询的DSL语句
     *
     * @param searchParam
     */
    private static SearchRequest builderDSL(SearchParam searchParam) {
        //          构建DSL语句
//          构建请求对象
        SearchRequest searchRequest = new SearchRequest("goods");
//        条件构造器
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//         多条件构造器
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

//检索的关键字
        String keyword = searchParam.getKeyword();
        if (!StringUtils.isEmpty(keyword)) {
/**
 * 多 个条件添加到must
 * "must": [
 *         {
 *           "match": {
 *             "title": {
 *               "query": "手机",             ---------------.matchQuery("title",keyword)
 *               "operator": "AND",           --------------.operator(Operator.AND)
 *               "prefix_length": 0,
 *               "max_expansions": 50,
 *               "fuzzy_transpositions": true,
 *               "lenient": false,
 *               "zero_terms_query": "NONE",
 *               "auto_generate_synonyms_phrase_query": true,
 *               "boost": 1
 *             }
 *           }
 *         }
 *       ],
 */
            boolQueryBuilder.must(QueryBuilders.matchQuery("title", keyword).operator(Operator.AND));
        }
        /**
         * 一二三级分类条件 过滤
         *
         * boolQueryBuilder.filter 是一个数组 里面存放多个term条件
         *"filter": [
         *         {
         *           "term": {
         *             "category3Id": {
         *               "value": 61,
         *               "boost": 1
         *             }
         *           }
         *         }
         *       ],
         */
        if (searchParam.getCategory1Id() != null && searchParam.getCategory1Id() == 0) {

//            当 terms 的个数较多时，TermsQuery 比多个 TermQuery 组合的查询效率更高。
//         boolQueryBuilder.filter(QueryBuilders.termsQuery("category1Id",searchParam.getCategory1Id())) ;

            boolQueryBuilder.filter(QueryBuilders.termQuery("category1Id", searchParam.getCategory1Id()));
        }

        if (searchParam.getCategory2Id() != null && searchParam.getCategory2Id() == 0) {

//            当 terms 的个数较多时，TermsQuery 比多个 TermQuery 组合的查询效率更高。
//         boolQueryBuilder.filter(QueryBuilders.termsQuery("category1Id",searchParam.getCategory1Id())) ;

            boolQueryBuilder.filter(QueryBuilders.termQuery("category2Id", searchParam.getCategory2Id()));
        }

        if (searchParam.getCategory3Id() != null && searchParam.getCategory3Id() == 0) {

//            当 terms 的个数较多时，TermsQuery 比多个 TermQuery 组合的查询效率更高。
//         boolQueryBuilder.filter(QueryBuilders.termsQuery("category1Id",searchParam.getCategory1Id())) ;

            boolQueryBuilder.filter(QueryBuilders.termQuery("category3Id", searchParam.getCategory3Id()));
        }

/**      判断品牌  1:小米 3: 华为
 * {
 *           "term": {
 *             "tmId": "1"
 *           }
 */
        String trademark = searchParam.getTrademark();
        if (!StringUtils.isEmpty(trademark)) {

            //按照":"分组  即  1:小米->["1","小米"]
            String[] split = trademark.split(":");
            if (split != null && split.length == 2) {
                boolQueryBuilder.filter(QueryBuilders.termQuery("tmId", split[0]));
            }
        }
//                 页面提交的数组
        String[] props = searchParam.getProps();
        if (props != null && props.length > 0) {

            for (String prop : props) {
//            创建多条件对象
                BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
//            创建一个子多条件对象
                BoolQueryBuilder subBoolQuery = QueryBuilders.boolQuery();
//            形如  props=23:6G:运行内存
                String[] split = prop.split(":");
                /***     子查询条件对象
                 *     "query": {
                 *                   "bool": {
                 *                     "filter": [
                 *                       {
                 *                         "term": {
                 *                           "attrs.attrId": "23"
                 *                         }
                 *                       },
                 *                       {
                 *                         "term": {
                 *                           "attrs.attrValue": "6G"
                 *                         }
                 *                       }
                 *                     ]
                 *                   }
                 *                 }
                 */
                if (split != null && split.length == 3) {
                    subBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", split[0]));
                    subBoolQuery.must(QueryBuilders.termQuery("attrs.attrValue", split[1]));
                }
                /**给子查询对象套一层attrs
                 * 这时候 用nested
                 *
                 * "attrs": 这是嵌套对象的字段名称。嵌套对象是包含其他字段的文档字段。
                 * subBoolQuery: 这是一个子布尔查询，用于指定在嵌套对象中匹配的条件。
                 * ScoreMode.None: 这是一个得分模式参数，用于指定如何计算查询得分。
                 * 在这种情况下，设置为 None 表示不计算得分。
                 */
                boolQuery.must(QueryBuilders.nestedQuery("attrs", subBoolQuery, ScoreMode.None));
//                将嵌套好的 子查询对象 放到外层的条件构造器
                boolQueryBuilder.filter(boolQuery);
            }
        }
//        将多条件 query里面查询的条件封装到最外层的条件查询器
        searchSourceBuilder.query(boolQueryBuilder);


//   -----------------------排序------sort------------------------
//        order=1:asc 热点排序 order=1:desc  | order=2:asc  order=2:desc  价格排序===1:hotScore 2:price
        String order = searchParam.getOrder();
        if (!StringUtils.isEmpty(order)) {
//            截取
            String[] split = order.split(":");
            if (split != null && split.length == 2) {
                String filed = "";
                switch (split[0]) {
                    case "1":
                        filed = "hotScore";
                        break;

                    case "2":
                        filed = "price";
                        break;
                }
                searchSourceBuilder.sort(filed, "asc".equals(split[1]) ? SortOrder.ASC : SortOrder.DESC);
            }
        } else {
//            若为空 默认按照 hotScore排序
            searchSourceBuilder.sort("hotScore", SortOrder.DESC);
        }

//  -----------------高亮查询--------highlight----------------------
//        创建高亮对象
        HighlightBuilder highlightBuilder = new HighlightBuilder();
//         title字段高亮查询
        highlightBuilder.field("title");
//设置前缀
        highlightBuilder.preTags("<font color='red'>");
//        后缀
        highlightBuilder.postTags("</font>");
//        设置高亮
        searchSourceBuilder.highlighter(highlightBuilder);


// ----------------分页----查询-------------------
//起始页
        searchSourceBuilder.from((searchParam.getPageNo() - 1) * searchParam.getPageSize());
//每页的条数
        searchSourceBuilder.size(searchParam.getPageSize());

//  --------------品牌聚合--tmIdAgg------------------------------
        /***品牌聚合--aggs-
         * "tmIdAgg": {
         *       "terms": {
         *         "field": "tmId",
         *         "size": 10
         *       },
         *       "aggs": {
         *         "tmNameAgg": {
         *           "terms": {
         *             "field": "tmName",
         *             "size": 10
         *           }
         *         },
         *         "tmLogoUrlAgg": {
         *           "terms": {
         *             "field": "tmLogoUrl",
         *             "size": 10
         *           }
         *         }
         *       }
         *     },
         */
        TermsAggregationBuilder termsAggregationBuilder = AggregationBuilders.terms("tmIdAgg").field("tmId").size(10)
                .subAggregation(AggregationBuilders.terms("tmNameAgg").field("tmName").size(10))
                .subAggregation(AggregationBuilders.terms("tmLogoUrlAgg").field("tmLogoUrl").size(10));

        searchSourceBuilder.aggregation(termsAggregationBuilder);
//-------------------平台属性 ----------attrsAgg---------------
        /**平台属性 ---
         *  "attrsAgg": {
         *       "nested": {
         *         "path": "attrs"
         *       },
         *       "aggs": {
         *         "attrIdAgg": {
         *           "terms": {
         *             "field": "attrs.attrId",
         *             "size": 10
         *           },
         *           "aggs": {
         *             "attrNameAgg": {
         *               "terms": {
         *                 "field": "attrs.attrName",
         *                 "size": 10
         *               }
         *             },
         *             "attrValueAgg": {
         *               "terms": {
         *                 "field": "attrs.attrValue",
         *                 "size": 10
         *               }
         *             }
         *           }
         *         }
         *       }
         *     }
         */
        searchSourceBuilder.aggregation(AggregationBuilders.nested("attrsAgg", "attrs")
                .subAggregation(
                        AggregationBuilders.terms("attrIdAgg").field("attrs.attrId")
                        .subAggregation(AggregationBuilders.terms("attrNameAgg").field("attrs.attrName"))
//                                括号没有匹配 多了一层 导致查询的数据 会多一个buckets桶
                        .subAggregation(AggregationBuilders.terms("attrValueAgg").field("attrs.attrValue"))

                ));
//  ------------结果集--------_source--------------------------
        /***---结果集--------_source---
         * "_source": [
         *     "id",
         *     "title",
         *     "defaultImg",
         *     "price"
         *   ]
         */

        searchSourceBuilder.fetchSource(new String[]{
                "id",
                "title",
                "defaultImg",
                "price"
        }, null);

//        System.out.println("searchSourceBuilde查询jsonstring = " + searchSourceBuilder.toString());
//        将构造的条件构造器 封装成一个请求对象
        searchRequest.source(searchSourceBuilder);
        return searchRequest;
    }

    /**
     * 更新商品的热度排名
     *
     * @param skuId
     */
    @Override
    public void incrHotScore(Long skuId) {
//        使用redis 保证让原子性操作 es不用平凡修改 当到达某一个值 在去es修改
        String hotKey = "hotscore";
//        点击一下 增量加一  访问详情页即+1 redis用zset存储 因其自带score分数

//        incrementScore(类似mysql表名, 主键, 增量)

        Double count = redisTemplate.opsForZSet().incrementScore(hotKey, "skuId:" + skuId, 1);
//redis里面点击量 每过10次 再到es里面保存
        if (count % 10 == 0) {

//  获取对象 Optional对象 内部自带非空判断 防止空指针
//        Optional<Goods> optionalGoods = goodsRepository.findById(skuId);
            Goods goods = goodsRepository.findById(skuId).get();
//        判断
            if (!ObjectUtils.isEmpty(goods)) {
//            Long hotScore = goods.getHotScore();
//                修改点击量
//                goods.setHotScore(Long.parseLong(String.valueOf(count)));
                goods.setHotScore(Math.round(count));
//                保存

                goodsRepository.save(goods);

            }
        }
    }

    /**
     * 商品下架
     *
     * @param skuId
     */
    @Override
    public void lowerGoods(Long skuId) {
        goodsRepository.deleteById(skuId);
    }

    /*  public static void main(String[] args) {
        BaseCategoryView baseCategoryView = new BaseCategoryView();
        baseCategoryView.setId(123l);
        baseCategoryView.setCategory1Id(11l);
        baseCategoryView.setCategory1Name("llname");
        baseCategoryView.setCategory2Id(22l);
        baseCategoryView.setCategory2Name("22name");
        baseCategoryView.setCategory3Id(33l);
        baseCategoryView.setCategory3Name("33name");
        System.out.println("baseCategoryView = " + baseCategoryView);
        Goods goods = new Goods();
        try {
            Map resource = PropertyUtils.describe(baseCategoryView);
            resource.remove("id" );
            System.out.println("resource = " + resource);
            BeanUtils.copyProperties(resource,goods);
        } catch (Exception e) {
          e.printStackTrace();
        }
        System.out.println("goods = " + goods);

    }*/

    /**
     * 商品上架
     *
     * @param skuId
     */
    @Override
    public void upperGoods(Long skuId) {
        //创建商品对象
        Goods goods = new Goods();
//        获取 skuInfo
        SkuInfo skuInfo = productFeignClient.getSkuInfo(skuId);
        if (!ObjectUtils.isEmpty(skuInfo)) {
//            BeanUtils.copyProperties(skuInfo,goods);属性名称和类型一样方可使用

            goods.setId(skuId);
            goods.setDefaultImg(skuInfo.getSkuDefaultImg());
            goods.setTitle(skuInfo.getSkuName());
//               goods.setPrice 需要的是double值   skuInfo.getPrice()是一个 BigDecimal 值
            goods.setPrice(skuInfo.getPrice().doubleValue());
            goods.setCreateTime(new Date());
//品牌查询
            BaseTrademark trademark = productFeignClient.getTrademark(skuInfo.getTmId());
            goods.setTmId(trademark.getId());
            goods.setTmName(trademark.getTmName());
            goods.setTmLogoUrl(trademark.getLogoUrl());
//三级分类查询
            BaseCategoryView categoryView = productFeignClient.getCategoryView(skuInfo.getCategory3Id());
            goods.setCategory1Id(categoryView.getCategory1Id());
            goods.setCategory1Name(categoryView.getCategory1Name());

            goods.setCategory2Id(categoryView.getCategory2Id());
            goods.setCategory2Name(categoryView.getCategory2Name());

            goods.setCategory3Id(categoryView.getCategory3Id());
            goods.setCategory3Name(categoryView.getCategory3Name());
//查询平台属性
            List<BaseAttrInfo> attrList = productFeignClient.getAttrList(skuId);
            if (!ObjectUtils.isEmpty(attrList)) {

                List<SearchAttr> searchAttrList = attrList.stream().map(baseAttrInfo -> {
//                   创建 SearchAttr
                    SearchAttr searchAttr = new SearchAttr();
                    searchAttr.setAttrId(baseAttrInfo.getId());
                    searchAttr.setAttrName(baseAttrInfo.getAttrName());
                    searchAttr.setAttrValue(baseAttrInfo.getAttrValueList().get(0).getValueName());
                    return searchAttr;
                }).collect(Collectors.toList());

                goods.setAttrs(searchAttrList);
            }

        }


//保存到elasticsearch 即上架
        goodsRepository.save(goods);
    }
}
